package Pet.Management.controller;

import Pet.Management.domain.dto.UserDataDTO;
import Pet.Management.service.UserDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/user-data")
public class UserDataController {

    @Autowired
    private UserDataService userDataService;

    @GetMapping("/list")
    public ResponseEntity<Map<String, Object>> getUserList(
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String authStatus,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        
        // 创建分页对象（注意：pageNum需要减1，因为Spring Data JPA的页码从0开始）
        PageRequest pageRequest = PageRequest.of(pageNum - 1, pageSize);
        
        // 获取分页数据
        Page<UserDataDTO> page = userDataService.getUserList(keyword, authStatus, pageRequest);
        
        Map<String, Object> response = new HashMap<>();
        response.put("total", page.getTotalElements());
        response.put("rows", page.getContent());
        
        return ResponseEntity.ok(response);
    }
    
    @GetMapping("/export")
    public ResponseEntity<Map<String, String>> exportUserData(
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String authStatus,
            HttpServletResponse response) throws IOException {
        
        // 导出全部数据，不分页
        PageRequest pageRequest = PageRequest.of(0, Integer.MAX_VALUE);
        Page<UserDataDTO> page = userDataService.getUserList(keyword, authStatus, pageRequest);
        List<UserDataDTO> userList = page.getContent();
        
        // 设置导出成功的消息
        Map<String, String> result = new HashMap<>();
        result.put("msg", "导出成功，共导出 " + userList.size() + " 条数据");
        
        return ResponseEntity.ok(result);
    }
} 